package com.example.jdk7;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class MyForkJoin extends RecursiveTask<Integer>{
    private static int ThreadHOLD=2;
    private int start;
    private int end;

    public MyForkJoin(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum=0;
        boolean canComp = (end-start)<ThreadHOLD;
        if(canComp){
            for (int i = start; i <=end ; i++) {
                sum+=i;
            }
        }else{
            int middle = (int) Math.floor((sum+end)/2);
            System.out.println("middle-"+middle);
            MyForkJoin leftTask = new MyForkJoin(start,middle);
            MyForkJoin rightTask = new MyForkJoin(middle+1,end);
            leftTask.fork();
            rightTask.fork();
            //等待任务完成


            int leftRet = leftTask.join();
            int rightRet = rightTask.join();
            sum = leftRet+rightRet;
        }
        return sum;
    }


    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        MyForkJoin task = new MyForkJoin(1,4);
        Future<Integer> result =forkJoinPool.submit(task);

        try {
            System.out.println(result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
